/*
 * @Author: zhangyujie
 * @Date:   2015-08-12 10:42:41
 * @Last Modified by:   LiNa
 * @Last Modified time: 2015-09-09 11:58:18
 */

define(['jquery', 'd3','util','hammer'], function($, d3,util,Hammer) {


    function doubleChart(url) {
        var setting = {
            selector: '#two_1',
            margin: {
                top: 10,
                left: 5,
                bottom: 20,
                right: 40
            },
            rectStyle: {
                'fill': '#8ac5fc'
            },
            pathStyle: {
                'fill': 'none',
                'stroke': '#ffc10e',
                'stroke-width': '2px'
            }

        }
        doubleChart(setting)

        function doubleChart(setting) {

            var width, height, selector,
                colorset, dom, position,
                name, value, i, serie,
                data, min, max, xScale,
                yScale, xScaleData, margin,
                contentW, contentH, xAxis, yAxis,
                valueLine, linearGradient, event, line,
                hightCircle, lowCircle

            var svg, content, left, right, ticks,
                lineWrap, total = [],
                income = [], monthAry = []

            d3.json(url, function(returnData) {

                var trueData = returnData.data

                trueData.forEach(function(e){
                    e.value[0]/=10000;
                    e.value[1]/=10000;
                });

                setting['series'] = trueData


                data = setting['series']
                selector = setting.selector
                dom = document.querySelector(selector)
                dom1 = document.querySelector(selector + " div")
                position = dom.getBoundingClientRect()
                position1 = dom1.getBoundingClientRect()
                var YrelcontentW = position.width
                var relcontentW = position1.width
                height = position.height
                colorset = setting.colorset


                margin = setting['margin']

                var num = []


                min = d3.min(data, function(d, i) {

                    return d3.min(d.value)
                })
                max = d3.max(data, function(d, i) {


                    return d3.max(d.value)
                })
                max = Math.ceil(max / 100) * 100

                var format = d3.time.format("%Y-%m")
                xScaleData = []

                var screenWidth = document.documentElement.clientWidth
                if (screenWidth == 375) {
                    var rectWidth = 26
                    var realWidth = data.length * rectWidth
                } else if (screenWidth > 375) {
                    var rectWidth = 29
                    var realWidth = data.length * rectWidth
                } else {
                    var rectWidth = 21.5
                    var realWidth = data.length *rectWidth
                }

                if (data.length > 12) {
                    data.forEach(function(d, i) {
                        var month = d.name.slice(-2)
                        if(month == '01') {
                            xScaleData.push(d.name.slice(0, 4))
                        } else {
                            xScaleData.push(month)
                        }
                        // xScaleData.push(format.parse(d.name))
                    })

                    var width = xScaleData.length * 0.1 * YrelcontentW
                    contentW = width - margin.left - margin.right
                    contentH = height - margin.top - margin.bottom

                    // xScale = d3.time.scale()
                    //     .domain(d3.extent(xScaleData))
                    //     .range([0, contentW])

                    xScale = d3.scale.ordinal()
                        .domain(d3.keys(xScaleData))
                        .rangeBands([0, contentW], 0.2)

                } else if (data.length <= 12) {
                    data.forEach(function(d, i) {
                        if (i == 0) {
                            xScaleData.push(d.name.slice(0,4))
                        } else {
                            xScaleData.push(d.name.slice(5))
                        }

                    })

                    var width = YrelcontentW

                    contentW = width - margin.left - margin.right

                    contentH = height - margin.top - margin.bottom

                    xScale = d3.scale.ordinal()
                        .domain(d3.keys(xScaleData))
                        .rangeBands([0, realWidth], 0)
                }



                var translate = (contentW / xScaleData.length) / 2


                // xAscale = d3.time.scale()
                //  .domain(d3.extent(xScaleData), function(d) {
                //      return xScaleData
                //  })
                //  .range([0, width])


                xAxis = d3.svg.axis()
                    .scale(xScale)
                    .orient('bottom')
                    .tickValues(d3.keys(xScaleData))
                    .tickSize(-contentH)


                svg = d3.select(selector + " div")
                    .append('svg')
                    .attr('width', width)
                    .attr('height', height)
                    .attr("class", "two_bar")

                var Ysvg = d3.select(selector)
                    .append('svg')
                    .attr('width', YrelcontentW)
                    .attr('height', height)

                svg.append('g')
                    .attr('class', 'axis')
                    .classed('xAxis', true)
                    .attr('transform', 'translate(' + margin.left + ',' + (margin.top + contentH) + ')')
                    .call(xAxis)

                svg.append('line')
                    .attr('x1', margin.left)
                    .attr("y1", margin.top)
                    .attr("x2", width)
                    .attr("y2", margin.top)
                    .attr("fill", "none")
                    .attr("stroke", "#F3F3F4")
                    .attr("stroke-width", "2px")

                svg.append('line')
                    .attr('x1', margin.left)
                    .attr("y1", margin.top + contentH)
                    .attr("x2", width)
                    .attr("y2", margin.top + contentH)
                    .attr("fill", "none")
                    .attr("stroke", "#F3F3F4")
                    .attr("stroke-width", "2px")

                for (var j = 0; j < xScaleData.length; j++) {
                    d3.select(svg.selectAll('.xAxis text')[j])
                        .text(function() {
                            for (var i = 0; i < xScaleData.length; i++) {
                                // if (data.length > 12) {
                                //     // $(this[i]).attr("x", translate)

                                // } else {
                                //     svg.select(".xAxis").selectAll("g line")
                                //             .attr("x2",-(rectWidth/2))
                                //             .attr("x1",-(rectWidth/2))
                                // }
                                svg.select(".xAxis").selectAll("g line")
                                    .attr("x2",-(rectWidth/2))
                                    .attr("x1",-(rectWidth/2))
                                $(this[i]).attr("class", function() {
                                    return "rect" + i
                                })
                                $(this[i]).attr("data", function() {
                                    return xScaleData[i]
                                })
                                d3.select(this[i]).text(xScaleData[i])

                                // if (d3.select(this[i]).text().indexOf("Feb") !== -1) {
                                //     d3.select(this[i]).text(2)
                                // } else if (d3.select(this[i]).text() == "March") {
                                //     d3.select(this[i]).text(3)
                                // } else if (d3.select(this[i]).text() == "April") {
                                //     d3.select(this[i]).text(4)
                                // } else if (d3.select(this[i]).text() == "May") {
                                //     d3.select(this[i]).text(5)
                                // } else if (d3.select(this[i]).text() == "June") {
                                //     d3.select(this[i]).text(6)
                                // } else if (d3.select(this[i]).text() == "July") {
                                //     d3.select(this[i]).text(7)
                                // } else if (d3.select(this[i]).text() == "August") {
                                //     d3.select(this[i]).text(8)
                                // } else if (d3.select(this[i]).text() == "September") {
                                //     d3.select(this[i]).text(9)
                                // } else if (d3.select(this[i]).text() == "October") {
                                //     d3.select(this[i]).text(10)
                                // } else if (d3.select(this[i]).text() == "November") {
                                //     d3.select(this[i]).text(11)
                                // } else if (d3.select(this[i]).text() == "December") {
                                //     d3.select(this[i]).text(12)
                                // }
                            }
                        })

                }

                yScale = d3.scale.linear()
                    .domain([max, 0])
                    .range([0, contentH])

                yAxis = d3.svg.axis()
                    .scale(yScale)
                    .orient('right')
                    .tickSize(0)
                Ysvg.append('g')
                    .attr('class', 'axis')
                    .classed('yAxis', true)
                    .attr('transform', 'translate(' + (YrelcontentW - margin.right) + ',' + margin.top + ')')
                    .call(yAxis)

                content = svg.append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

                linearGradient = content.append('defs')
                    .append('linearGradient')
                    .attr('id', 'mylinearGradient')
                    .attr('x1', '0%')
                    .attr('y1', ' 0%')
                    .attr('x2', '0%')
                    .attr('y2', '100%')

                linearGradient.append('stop')
                    .attr('offset', '50%')
                    .attr('stop-color', setting.rectStyle.fill)
                    .attr('stop-opacity', '1')

                linearGradient.append('stop')
                    .attr('offset', '100%')
                    .attr('stop-color', '#fff')
                    .attr('stop-opacity', '1')

                content.append('g').selectAll('rect')
                    .data(data)
                    .enter()
                    .append('rect')
                    .attr('x', function(d, i) {

                        return xScale(i)
                    })
                    .attr('y', function(d, i) {
                        return yScale(d.value[0])
                    })
                    .attr('width', 0)
                    .attr('height', function(d, i) {

                        return contentH - yScale(d.value[0])
                    })
                    .style(setting.rectStyle)
                    .style('fill', 'url(#mylinearGradient)')
                    .on('click', touch)
                    .transition()
                    .duration(2000)
                    .attr('width', function(d, i) {

                        if (data.length>12) {
                            return (contentW/xScaleData.length -1)
                        } else {
                            return rectWidth-1
                        }
                    })
                    .attr("data", function(d, i) {

                        return i
                    })


                valueLine = d3.svg.line()
                    .interpolate('linear')
                    .x(function(d, i) {
                        if (d.length>12) {
                            return xScale(i) + (contentW/xScaleData.length)/2
                        } else {
                            return xScale(i)+ rectWidth/2 + 4
                        }

                    })
                    .y(function(d) {

                        return yScale(d.value[1])
                    })

                content.append('g')
                    .append('path')
                    .attr('d', valueLine(data))
                    .style(setting.pathStyle)
                    .call(end)

                lineWrap = content.append('g')
                    .style('display', 'none')
                line = lineWrap.append('line')
                    .attr('x1', 0)
                    .attr('y1', 0)
                    .attr('x2', 0)
                    .attr('y2', contentH)
                    .style(setting.pathStyle)


                lowCircle = lineWrap.append('circle')
                    .attr('r', 6)
                    .attr('fill', setting.rectStyle.fill)
                    .attr('stroke-width', '2px')
                    .attr('stroke', '#fff')
                hightCircle = lineWrap.append('g')

                hightCircle.append('circle')
                    .attr('r', 10)
                    .attr('fill', '#fff')
                    .attr('stroke-width', '2px')
                    .attr('stroke', setting.pathStyle.stroke)

                hightCircle.append('circle')
                    .attr('r', 6)
                    .attr('fill', setting.pathStyle.stroke)



                svg.selectAll(".xAxis text")
                    .on('click', touch)



                // .on('touchend', function(d) {
                //  line
                //      .style('display', 'none')
                // })

                var hammertime = new Hammer(document.querySelector(".two_bar"));
                //添加事件
                var cur = 0

                var ulWidth = width

                var two_3 = $("#two_3").width()

                var diff_left = 0

                var currentStart = 0

                hammertime.on('panstart', function(e) {
                    //开始手势移动 记录当前位置
                    currentStart = parseFloat($(".two_bar").css("margin-left"))
                })

                hammertime.on("panmove", function(e) {
                    if (data.length <= 12) {
                        return
                    }
                    if (width == relcontentW) {
                        return
                    }

                    diff_left = currentStart + e.deltaX

                    //左边界
                    diff_left = Math.min(diff_left, 0)
                    //右边界
                    diff_left = Math.max(diff_left, -ulWidth + two_3 + contentW / xScaleData.length - margin.right * 2 / 3)

                    // 新位置 使用tansform 和margin-left是一样的效果
                    $(".two_bar").css("margin-left", diff_left)

                })

                function end(line) {
                    line.transition()
                        .duration(3000)
                        .attrTween("stroke-dasharray", tweenDash)
                        .attr('fill-opacity', 1)

                }

                function tweenDash() {
                    var l = this.getTotalLength(),
                        i = d3.interpolateString("0,kkk" + l, l + "," + l);
                    return function(t) {
                        return i(t);
                    }
                }

                function touch() {

                    var index1 = d3.select(this).attr("data")

                    num.push(setting.series[index1].value)
                    num = []
                    var target = null,
                        tagName, height,
                        position, left, key,
                        lineValue, rectValue,
                        index, arr

                    position = d3.mouse(dom)
                    target = d3.event.target
                    tagName = target.tagName


                    left = position[0] - margin.left - parseInt($(".two_bar").css("margin-left"))

                    arr = getData(left, index1)

                    index = arr[0]

                    if (index >= 0) {

                        lineWrap.style('display', 'block')
                        if (data.length>12) {
                            line
                                .attr('transform', 'translate(' + (xScale(index1) + (contentW / xScaleData.length / 2)) + ',' + 0 + ')')

                            lowCircle
                                .attr('transform', 'translate(' + (xScale(index1) + (contentW / xScaleData.length / 2)) + ',' + yScale(data[index1].value[0]) + ')')

                            hightCircle
                                .attr('transform', 'translate(' + (xScale(index1) + (contentW / xScaleData.length / 2)) + ',' + yScale(data[index1].value[1]) + ')')
                        } else {
                            line
                                .attr('transform', 'translate(' + (xScale(index1) + (rectWidth / 2)) + ',' + 0 + ')')

                            lowCircle
                                .attr('transform', 'translate(' + (xScale(index1) + (rectWidth / 2)) + ',' + yScale(data[index1].value[0]) + ')')

                            hightCircle
                                .attr('transform', 'translate(' + (xScale(index1) + (rectWidth / 2)) + ',' + yScale(data[index1].value[1]) + ')')
                        }

                    }

                }

                function getData(num, index) {

                    var unitData = contentW / xScaleData.length,
                        preIndex,
                        nextIndex, currentIndex, k,
                        vaildIndex, y, currentValue, vaildValue, x, b


                    var currentIndex = Math.floor(num / unitData)

                    if (currentIndex < 0) {

                        currentIndex = 0
                    }

                    if (currentIndex > xScaleData.length - 1) {

                        currentIndex = xScaleData.length - 1
                    }
                    preIndex = currentIndex - 1

                    nextIndex = currentIndex + 1

                    if ((num / unitData) - currentIndex >= 0.5) {

                        vaildIndex = nextIndex

                    } else {

                        vaildIndex = preIndex
                    }

                    if (vaildIndex <= -1 || vaildIndex >= xScaleData.length - 1) {

                        vaildIndex = currentIndex
                    }

                    currentValue = yScale(data[currentIndex].value[1])

                    vaildValue = yScale(data[vaildIndex].value[1])

                    if (currentIndex >= vaildIndex) {

                        x = num - (currentIndex * unitData) + translate

                        k = -1

                        b = vaildValue
                    } else {

                        x = num - (currentIndex * unitData) - translate


                        k = 1

                        b = currentValue
                    }
                    y = k * (vaildValue - currentValue) * x / unitData + b

                    return [index, y]
                }


            })



        }

    }

    return {
        doubleChart: doubleChart
    }

})